// index.js
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const fs = require('fs');
const path = require('path');
const cors = require('cors');
const logger = require('./logger');
const { SocksProxyAgent } = require('socks-proxy-agent');

const app = express();
const configPath = path.join(__dirname, 'config.json');

// socks代理agent将根据配置创建
let agent = null;

// 启用CORS
app.use(cors());

// 请求日志中间件
app.use((req, res, next) => {
  logger.info('Incoming request', {
    method: req.method,
    url: req.url,
    query: req.query,
    headers: req.headers,
    ip: req.ip
  });

  // 记录响应时间
  const start = Date.now();
  res.on('finish', () => {
    const duration = Date.now() - start;
    logger.info('Request completed', {
      method: req.method,
      url: req.url,
      status: res.statusCode,
      duration: `${duration}ms`
    });
  });

  next();
});

// 读取配置文件函数
function loadConfig() {
  try {
    const configData = fs.readFileSync(configPath, 'utf8');
    const config = JSON.parse(configData);
    logger.info('Configuration loaded successfully', { 
      proxiesCount: config.proxies.length 
    });
    return config;
  } catch (error) {
    logger.error('Failed to load config file', { 
      error: error.message,
      stack: error.stack 
    });
    process.exit(1);
  }
}

// 配置代理函数
function setupProxies(app, config) {
  // 清除现有的代理路由
  app._router.stack = app._router.stack.filter(layer => !layer.route && layer.name !== 'proxy');
  logger.info('Cleared existing proxy routes');

  // 根据配置决定是否创建socks代理
  if (config.useSocksProxy) {
    const socksConfig = config.socksProxy || {};
    const host = socksConfig.host || '127.0.0.1';
    const port = socksConfig.port || 1080;
    const protocol = socksConfig.protocol || 'socks5';
    
    agent = new SocksProxyAgent({
      hostname: host,
      port: port,
      protocol: protocol
    });
    logger.info('SOCKS proxy enabled', { host, port, protocol });
  } else {
    agent = null;
    logger.info('SOCKS proxy disabled');
  }

  config.proxies.forEach(proxy => {
    // 创建代理中间件配置
    const proxyOptions = {
      target: proxy.target,
      changeOrigin: true,
      pathRewrite: proxy.pathRewrite || {},
      onProxyRes: function (proxyRes, req, res) {
        proxyRes.headers['Access-Control-Allow-Origin'] = '*';
        logger.debug('Proxy response received', {
          path: req.url,
          status: proxyRes.statusCode,
          target: proxy.target
        });
      },
      onError: function (err, req, res) {
        logger.error('Proxy error occurred', {
          path: proxy.path,
          target: proxy.target,
          error: err.message,
          stack: err.stack
        });
        res.status(500).send(`Proxy error: ${err.message}`);
      },
      proxyTimeout: 30000, // 30 seconds timeout
      timeout: 30000,
    };

    // 如果启用了socks代理且当前代理配置也需要使用socks代理
    if (agent && (proxy.useSocksProxy !== false)) {
      proxyOptions.agent = agent;
      logger.debug('Using SOCKS proxy for', { path: proxy.path, target: proxy.target });
    }

    const apiProxy = createProxyMiddleware(proxyOptions);

    // 使用代理中间件处理请求
    app.use(proxy.path, apiProxy);
    logger.info('Proxy route configured', {
      path: proxy.path,
      target: proxy.target,
      pathRewrite: proxy.pathRewrite,
      usingSocksProxy: proxyOptions.agent ? true : false
    });
  });
}

// 初始化代理配置
let proxyConfig = loadConfig();
setupProxies(app, proxyConfig);

// 监听配置文件变化
fs.watch(configPath, (eventType) => {
  if (eventType === 'change') {
    logger.info('Config file change detected');
    try {
      const newConfig = loadConfig();
      setupProxies(app, newConfig);
      proxyConfig = newConfig;
      logger.info('Proxy configuration reloaded successfully');
    } catch (error) {
      logger.error('Failed to reload config', {
        error: error.message,
        stack: error.stack
      });
    }
  }
});

// 处理根路径请求
app.get('/', (req, res) => {
  logger.info('Root path accessed');
  res.send('API Proxy');
});

// 优雅关闭处理
process.on('SIGTERM', () => {
  logger.info('SIGTERM received. Starting graceful shutdown...');
  // 关闭服务器
  server.close(() => {
    logger.info('Server closed');
    process.exit(0);
  });
});

// 为本地测试添加的代码
const PORT = process.env.PORT || 80;

// 添加启动前日志
logger.debug('Starting API Proxy server...');

const server = app.listen(PORT, () => {
  logger.info('✅ Server started successfully', {
    port: PORT,
    nodeEnv: process.env.NODE_ENV || 'development',
    pid: process.pid
  });
  
  // 输出代理配置摘要
  logger.info('Current proxy configuration:', {
    useSocksProxy: proxyConfig.useSocksProxy,
    socksProxyConfig: proxyConfig.socksProxy,
    proxyCount: proxyConfig.proxies.length,
    proxyPaths: proxyConfig.proxies.map(p => p.path).join(', ')
  });
  
  logger.info('Server is ready to accept connections');
});

// 添加启动失败处理
server.on('error', (error) => {
  logger.error('Failed to start server', {
    error: error.message,
    stack: error.stack,
    port: PORT
  });
  
  if (error.code === 'EACCES') {
    logger.error('Permission denied. Try using a different port or running with elevated privileges.');
  } else if (error.code === 'EADDRINUSE') {
    logger.error('Port is already in use. Try using a different port or stopping the process using this port.');
  }
  
  process.exit(1);
});